<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UsersController extends AppController {

    public $helpers = array('Html', 'Form');
    var $components = array('Email');

    public function index() {
        $this->set('ad', $this->Auth->user('admin'));
    }
    
    public function manage() {
        $usersArray = $this->User->getAllUsers();
        $length = count($usersArray);
        //get the signed in user
        $caller = $this->Auth->user('userID');
        $deletedusersArray = $this->User->getDeletedUsers();
        $deletedlength = count($deletedusersArray);
        //get the signed in user
        //send the parameters to the coresponding view 
        $admin = $this->User->isAdmin($caller);
        if ($admin == 1) {
            $this->set('admin', $admin);
            $this->set('caller', $caller);
            $this->set('usersArray', $usersArray);
            $this->set('length', $length);
            $this->set('l', $length);
            $this->set('deletedusersArray', $deletedusersArray);
            $this->set('deletedlength', $deletedlength);
            $this->set('deletedl', $deletedlength);
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
    }
    /*
     * Description of "add"
     *
     * the function takes the new user data from add user form and saves it in the database if valid data else it asks for re-entering the data.
     * 
     * @author "Mohamed Elhawary"
     */

    public function add() {
        $this->set('admin',$this->Auth->user('admin'));
        if ($this->request->is('post')) {
            if ($this->data['User']['admin'] == 0) {
                $this->request->data['User']['admin'] = false;
            }
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('user added successfully to the system');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('The user could not be saved. Please, try again.');
            }
        }
    }

    /*
     * Description of "login"
     *
     * The function checks if the given information in the login form is valid and redirects the user to dashboard if valid and asks for reentry otherwise.
     * 
     * @author "Mohamed Elhawary"
     */

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login() && !empty($this->request->data['User'])) {
                if ($this->Auth->user('deleted')) {
                    $this->Session->setFlash('this user has been deleted');
                    $this->redirect(array('controller' => 'Users', 'action' => 'logout'));
                } else {

                   if ($this->Auth->user('accID')==null) {
                        $this->redirect($this->Auth->redirect('/posts/fetchHome'));
                    } else {
                        $this->redirect($this->Auth->redirect('/posts/fetchHome'));
                    }
                }
            } else {
                $this->Session->setFlash('incorrect user name or password');
            }
        }
    }
/*
     * Description of "fb_login"
     *
     * This function checks if the logged in facebook user is linked to one of the system users through the facebook ID
     * if true the user is logged in else if false it redirects to the logout and set the flash to access denied
     *
     * @author "Karim Kamel"
     */

    public function fb_login() {
        $result = $this->User->find('all', array('conditions' => array('facebook_id' => $_SESSION['fb_229252837184673_user_id'])));
        if ($this->Auth->login($result['0']['User'])) {

            $this->redirect(array('controller' => 'Posts', 'action' => 'fetchHome'));
        } else {

            $this->redirect(array('controller' => 'Users', 'action' => 'logout'));
        }
    }

    /*
     * Description of "fb_connect"
     *
     * This function takes the facebook id of the facebook logged in user and insert 
     * it in the database in the row of the system logged in user
     *
     * @author "Karim Kamel"
     */

    public function fb_connect() {
        $facebook_id = $_SESSION['fb_229252837184673_user_id'];
        $result = $this->User->find('all', array('conditions' => array('facebook_id' => $facebook_id)));
        if ($result) {
            $this->Session->setFlash("This facebook account is already connected to Tattlr either by you or someone else, please Logout and try again");
        } else {
            if ($this->User->updateAll(array('facebook_id' => $facebook_id), array('userID' => $this->Auth->user()))) {
                $this->redirect(array('controller' => 'Posts', 'action' => 'fetchHome'));
            } else {

                $this->Session->setFlash('Something went wrong, Please try again');
            }
        }
    }

    /*
     * Description of "logout"
     *
     * the function redirects the user to login page and deletes Session data.
     * 
     * @author "Mohamed Elhawary"
     */

    function logout() {
        $this->redirect($this->Auth->logout());
    }

    public function isAuthorized($user) {
        parent::isAuthorized($user);
        if ($this->action == 'add') {
            if ($user['admin']) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * This method sends the users list to the view and  the caller of the delete function
     *
     * @access: public
     * @param: array $usersArray; 3d array of the non deleted users IDs
     * @param: int $length; the number of non deleted users
     * @param: int $caller; the user ID of the signed in user
     * @author "Mina Farag"
     */
        public function delete() {
        $usersArray = $this->User->getAllUsers();
        $length = count($usersArray);
        //get the signed in user
        $caller = $this->Auth->user('userID');
        //send the parameters to the coresponding view 
        $admin = $this->User->isAdmin($caller);
        if ($admin == 1) {
            $this->set('admin', $admin);
            $this->set('caller', $caller);
            $this->set('usersArray', $usersArray);
            $this->set('length', $length);
            $this->set('l', $length);
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
    }

    /**
     * This method calls the deleteUser function from the user model
     *
     * @access: public
     * 
     * @param: int $userID; the user i want to delete
     * @param: int $caller; the user ID of the signed in user
     * @author "Mina Farag"
     */
    public function delete1($userid) {

        $caller = $this->Auth->user('userID');
        //call the deleteUser function from the user model 
        $message = $this->User->deleteUser($caller, $userid);
        //set a deletion status message linked to the dash board URL
        $this->redirect('/users/manage');
    }


    /**
     * Description of viewUsers():
     * @param void
     * @return void
     * @access public
     * 
     * Description of the function: 
     * A function gets the user ID and account ID from the session, handles them to the model
     * and then views a list with check boxes of existing users working for the same account  
     * 
     * @author "OmarElshal"
     */
    function viewUsers() {
        $accID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        //debug($userID);

        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID);
		
		if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        if ($this->Auth->User('admin')) {

            $result = $this->User->viewUsers($userID, $accID);

            if ($result == 0) {
                $this->Session->setFlash('No users yet in the database');
            } else if (!empty($result)) {
                $this->set('result', $result);
            } else {
                $this->Session->setFlash('There are no users for this account yet');
                $this->redirect(array('controller' => 'users', 'action' => 'index'));
                $this->set('result', NULL);
            }
        } else {
            $this->Session->setFlash('You are not authorized to view this page!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
            $this->set('result', NULL);
        }
    }

    /**
     * This method sends the users list to the view and  the caller of the restore function
     *
     * @access: public
     * @param: array $usersArray; 3d array of the deleted users IDs
     * @param: int $length; the number of  deleted users
     * @param: int $caller; the user ID of the signed in user
     * the function checks the permission of its caller if he is an admin 
     * then the deleted users array and other parameters are sent to the view
     * else a flash message is set declaring that this user is not authorized
     * to view this page
     * @author "Mina Farag"
     */
    public function restore() {
        $usersArray = $this->User->getDeletedUsers();
        $length = count($usersArray);
        //get the signed in user
        $caller = $this->Auth->user('userID');
        //send the parameters to the coresponding view 
        $admin = $this->User->isAdmin($caller);
        if ($admin == 1) {
            $this->set('admin', $admin);
            $this->set('caller', $caller);
            $this->set('usersArray', $usersArray);
            $this->set('length', $length);
            $this->set('l', $length);
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
    }

    /**
     * This method calls the restoreUser function from the user model
     *
     * @access: public
     * 
     * @param: int $userID; the user i want to restore
     * @param: int $caller; the user ID of the signed in user
     * @author "Mina Farag"
     */
    public function restore1($userid) {

        $caller = $this->Auth->user('userID');
        //call the restoreUser function from the user model 
        $message = $this->User->restoreUser($caller, $userid);
        //set a restore status message linked to the restore page URL
        $this->redirect('/users/manage');
    }
    
    /**
     * This method checks if the mail entered is valid and then calls createTempPassword() from the user model and sends an email to the user with the new 
     *password
     * @access: default
     * 
     * @param: array $email; the array of cakeEmail parameters
     * @param: array $user; the user corresponding to this mail
     * @param: String $tmp_pass; a string of length 8 of a randomly generated password
     * @param: String $body; the body of the mail sent 
     * 
     * the method is called from the forgot password view , a mail new cakeEmail is initiated and if the user corresponding with
     * the mail entered is found then the function called the createTempPassword()from the user model and a new password is generated for this user
     * and it is sent to the mail .
     * 
     * 
     * @author "Mina Farag"
     */
    
    
    function forgotpassword() {
        App::uses('CakeEmail', 'Network/Email');
        $email = new CakeEmail('default');

        if (!empty($this->data)) {
            $this->User->recursive = 0;
            $user = $this->User->findByEmail($this->data['User']['email']);
            if ($user && $user['User']['deleted']==0) {
                $tmp_pass = $this->User->createTempPassword(8, $user['User']['userID']);

                $body = "Please visit  /users/login 
Your new password: {$tmp_pass}";

                if ($email->from(array('mina.farouj@gmail.com' => __('Tattlr')))
                                ->to($user['User']['email'])
                                ->subject(__('New Password'))
                                ->send(__($body))) {
                    $this->Session->setFlash(__('Your new password 
has been sent, please check your inbox', true), 'warning');
                } else {
                    $this->Session->setFlash(__('Failed to send the 
confirmation email. Please contact the administrator at support@xxx', true), 'error');
                }
                $this->redirect(array('controller' => 'users',
                    'action' => 'login'));
            }
        } else {
            $this->Session->setFlash('No user was found with the submitted 
email address.');
        }
    }
    
    /**
     *@author Moataz Ezzo
     *This function takes userID as an input and returns its user
     */
    function viewProfiles(){
	$userID = $this->Auth->User('userID');
	$this->User->id = $userID;
	$user = $this->User->getProfile($userID);
	$y;
	if($user==null){
	    $this->Session->setFlash('you are not signed in.');
            return $this->redirect('/users/index/');
	}
	foreach ($users as $user) {
	$y[0]['fullname'] = $user['users']['fullname'];
        $y[0]['image'] = $user['users']['image'];
        $y[0]['email'] = $user['users']['email'];
	}
	$this->set('user', $y);
	
	if ($this->request->is('post')){
			$this->User->set( $this->request->data );
			if($this->User->saveField('fullname',$this->request->data['user']['fullname'])){
				$this->Session->setFlash('changes saved sucessfully');
				$this->redirect(array('controller' => 'users','action' => 'index'));
			}
			else{
				$this->Session->setFlash('data could not be saved , please try again');
    }



}}}

?>
